package com.chuantou.yuba.api.request;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map;

import android.net.Uri;
import android.net.Uri.Builder;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class GsonListRequest<T> extends BaseGsonRequest<T> {
	private Type mType;
	private Listener<T> mResponseListener;

	public GsonListRequest(int method, String url, Listener<T> responseListener, ErrorListener listener, Map<String, String> params, Type type) {
		super(method, url, params, listener);
		this.mResponseListener = responseListener;
		this.mType = type;
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		String responseStr;
		try {
			responseStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
		} catch (UnsupportedEncodingException e) {
			responseStr = new String(response.data);
		}
		try {
			Gson gson = createGson();
			T result = gson.fromJson(responseStr, mType);
			return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
			return Response.error(new ParseError(e));
		}
	}

	@Override
	protected void deliverResponse(T response) {
		if (mResponseListener != null) {
			mResponseListener.onResponse(response);
		}
	}

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		return mApiContext.getHeaders();
	}

	@Override
	public String getUrl() {
		if (getMethod() == Method.GET && mParams != null && !mParams.isEmpty()) {
			Builder builder = Uri.parse(super.getUrl()).buildUpon();
			for (String key : mParams.keySet()) {
				builder.appendQueryParameter(key, mParams.get(key));
			}
			return builder.toString();
		}
		return super.getUrl();
	}

	@Override
	public String getCacheKey() {
		if (getMethod() == Method.POST && mParams != null && !mParams.isEmpty()) {
			Builder builder = Uri.parse(super.getUrl()).buildUpon();
			for (String key : mParams.keySet()) {
				builder.appendQueryParameter(key, mParams.get(key));
			}
			return builder.toString();
		}
		return getUrl();
	}
}
